//文件上传
//导入express
const express = require("express")
//创建Router实例
const router = express.Router()

const path = require("path")

const xlsx = require("xlsx")

const {upload} = require("../utils/file");
const {filePath} = require("../config");

//单文件上传
router.post("/upload", upload.single("file"), (req, res) => {
    res.send({
        status: 0,
        message: "文件上传成功",
        data: {
            fileId: req.file.filename,
            fileName: req.file.originalname,
            fileSize: req.file.size,
            fileFormat: path.extname(req.file.originalname).slice(1)
        },
    })
})

//多文件上传

router.post("/multipleUpload", upload.array(['files']), (req, res) => {
    let files = req.files.map(item => {
        return {
            fileId: item.filename,
            fileName: item.originalname,
            fileSize: item.size,
            fileFormat: path.extname(item.originalname).slice(1)
        }
    })
    res.send({
        status: 1,
        message: "文件上传成功",
        data: files
    })
})

// 预览上传的图片
router.get(`/${filePath}:filename`, (req, res) => {
    let filename = path.join(path.resolve(__dirname), '../', filePath, req.params.filename);
    res.sendFile(filename);
});

//excel转html
router.post("/excelToHtml", upload.single("materialsBill"), (req, res) => {

    if (!req.file) {
        return res.status(400).send('No files were uploaded.');
    }
    const filePaths = path.join(__dirname, '../', filePath, req.file.filename);
    const workbook = xlsx.readFile(filePaths, {cellStyles: true});
    const sheet_name = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheet_name];
    const htmlTable = xlsx.utils.sheet_to_html(worksheet, {editable: true});
    const editable_html = htmlTable.match(/<table[^>]*>([\s\S]*?)<\/table>/i);
    res.send({
        code: 200,
        message: "文件转换成功",
        data: editable_html && editable_html[0],
    })
})

//导出router模块
module.exports = router;

